package com.test45_JUC;

import java.util.concurrent.Exchanger;
import java.util.concurrent.TimeUnit;

/**
 * Exchanger：交换空间
 * 它主要的功能就是完成生产者和消费者之间数据传输处理
 */
public class Demo14_Exchanger {

    public static void main(String[] args) throws Exception {
        int repeat = 20;    // 定义生产和消费的次数
        Exchanger<String> exchanger = new Exchanger<>();

        new Thread(() -> {
            for (int x = 0; x < repeat; x++) {  // 生产的次数
                String info = null;
                if (x % 2 == 0) {
                    info = "李兴华高薪就业编程训练营：edu.yootk.com";
                } else {
                    info = "沐言科技：www.yootk.com";
                }
                try {
                    TimeUnit.MILLISECONDS.sleep(500);
                    System.out.printf("【%s】%s%n", Thread.currentThread().getName(), info);
                    exchanger.exchange(info);   // 数据存储
                } catch (InterruptedException e) {}
            }
        }, "生产者").start();

        new Thread(() -> {
            for (int x = 0; x < repeat; x++) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    String info = exchanger.exchange(null);  // 数据获取
                    System.err.printf("【%s】%s%n", Thread.currentThread().getName(), info);
                } catch (InterruptedException e) {}
            }
        }, "消费者").start();
    }
}
